var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser=require('body-parser');
//全局封装token 1.引入token模块
var jwt=require('jsonwebtoken')
var cors=require('cors')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 设置跨域
var allowCrossDomain = (req, res, next) => {
  // 所有接口均可以访问服务器
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', '*')
  next()
}

//引入接口文件
var bannerApi=require('./api/banner');
var categoryApi=require('./api/category');
var productApi = require('./api/product');//详情接口
var searchApi = require('./api/search');//搜索接口
var usersApi = require('./api/users');
var cartApi = require('./api/cart');
var orderApi = require('./api/order');
var addressApi = require('./api/address');
var homepicApi = require('./api/homepic');
var app = express();

app.use(allowCrossDomain)
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json({limit:'50mb'}))
app.use(bodyParser.urlencoded({limit:'50mb',extended:true}))
app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

//注册接口文件,加/api规范，避免冲突
app.use('/api/product',productApi)
app.use('/api/banner',bannerApi)
app.use('/api/category',categoryApi)
app.use('/api/users', usersApi);
app.use('/api/search', searchApi);
app.use('/api/cart', cartApi);
app.use('/api/order', orderApi);
app.use('/api/address', addressApi);
app.use('/api/homepic', homepicApi);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
